import time
import traceback

import requests
from PIL import ImageFont, Image

from framework import lib
from framework import struct


final = 1686067200


class MainPage(struct.Page):
    def __init__(self, book):
        super().__init__(book)
        self.env = book.base.env

        self._background = book.base.env.page_with_title_img
        self.font45 = ImageFont.truetype(
            "resources/fonts/PTSerifCaption.ttc", 45)

        # 倒计时控件
        self.add_element(lib.Elements.TextElement(self, (14, 57), '距离高考'))
        self.last = self.add_element(lib.Elements.TextElement(self, (12, 59), '365', self.font45))
        self.add_element(lib.Elements.TextElement(self, (93, 93), '天'))
        self.pro = self.add_element(lib.Elements.ProgressBar(self, (12, 110), 234, 5, 1, 20))
        self.pro_t = self.add_element(lib.Elements.Label(self, (246, 106), (48, 16), text="100%", border=(2, 2),
                                                         align="center"))

        # 时间控件
        self.date = self.add_element(lib.Elements.Label(self, (5, 0), size=(286, 30), border=(5, 8), font_size=16,
                                                        align="left"))
        self.clock = self.add_element(lib.Elements.Label(self, (5, 0), size=(286, 30), border=(5, 8), font_size=16,
                                                         align="right"))
        self.flag = False

        # 天气控件
        self.weather = self.add_element(lib.Elements.Label(self, (0, 30), size=(296, 30), border=(14, 6), text="加载中...", align="left",
                                            font_size=16))

        # 一言控件
        self.text = self.add_element(lib.Elements.MultiplePagesText(self, (120, 55), size=(170, 45), border=(5, 2), text="加载中..."))
        self.author = self.add_element(lib.Elements.Label(self, (125, 90), size=(170, 16), border=(5, 0), text="", align="right"))

    def pause(self):
        self.flag = False

    def clock_updater(self):
        last_clock = None
        last_date = None
        last_last = None
        while self.flag:
            now_clock = time.strftime("%H:%M", time.localtime())
            if last_clock != now_clock:
                self.clock.set_text(now_clock)
                last_clock = now_clock
            now_date = time.strftime("%Y年%m月%d日", time.localtime())
            if last_date != now_date:
                self.date.set_text(now_date)
                last_date = now_date
            now_last = str(int((final - time.time()) // 86400))
            if last_last != now_last:
                self.last.set_text(now_last)
                self.pro.set_value((365 - int(now_last)) / 365 * 100)
                self.pro_t.set_text(f"{(365 - int(now_last)) / 365 * 100:.0f}%")
                last_last = now_last
            time.sleep(2)

    def network_updater(self):
        while self.flag:
            self.weather.set_text(self.env.qweather.get_summary())
            time.sleep(600)

    def hitokoto_updater(self):
        while self.flag:
            try:
                response = requests.get("https://v1.hitokoto.cn/")
                response.raise_for_status()
                hitokoto = response.json()
                self.text.set_text(hitokoto["hitokoto"], False)
                self.author.set_text(f"--{hitokoto['creator']} 《{hitokoto['from']}》")
            except:
                self.env.Logger.error(traceback.format_exc())
                print(traceback.format_exc())
                time.sleep(5)
                continue
            time.sleep(300)


    def active(self):
        self.flag = True
        self.env.Pool.add(self.clock_updater)
        self.env.Pool.add(self.network_updater)
        self.env.Pool.add(self.hitokoto_updater)


class MainBook(struct.Book):
    def __init__(self, app):
        super().__init__(app)
        self.add_page("main", MainPage(self))


class Theme(lib.ThemeBase):
    def __init__(self, env):
        super().__init__(env)
        self.add_book("main", MainBook(self))
